import operator
from kiwi.core.base import Instances, Instance 

#*****************************************************************************
# PURPOSE: 
# USAGE:   
# PASSED ARGS:  
# RETURN ARGS: 
# Error - Fail Error Message
#*****************************************************************************
def SortDictByValue( dict, isReverse = False ):
	itemiters = dict.iteritems()	
	return sorted( itemiters, key = operator.itemgetter(1), reverse = isReverse )

#*****************************************************************************
# PURPOSE: 
# USAGE:   
# PASSED ARGS:  
# RETURN ARGS: 
# Error - Fail Error Message
#*****************************************************************************	
def SortInstancesByValue( instances, index = -1, isReverse = False ):
	valueCount = {}	
	for instance in instances:
		value = instance[ index ] 
		valueCount.setdefault( value, 0  )
		valueCount[ value ] += 1
	return 	SortDictByValue( valueCount, isReverse )

#*****************************************************************************
# PURPOSE: 
# USAGE:   
# PASSED ARGS:  
# RETURN ARGS: 
# Error - Fail Error Message
#*****************************************************************************		
def MajorityCnt( instances, index = -1 ):
	itemlist = SortInstancesByValue( instances, index  )
	print "ok"
	return itemlist[ -1 ]
	
#*****************************************************************************
# PURPOSE: 
# USAGE:   
# PASSED ARGS:  
# RETURN ARGS: 
# Error - Fail Error Message
#*****************************************************************************		
def MinorityCnt( instances, index = -1 ):
	itemlist = SortInstancesByValue( instances, index  )
	return itemlist[ 0 ]
